<template>
  <div class="container">
    <div v-if="postForm.templateType !== ''" class="template-preview">
      <h5 class="template-title">{{ renderTemplateTxt.templateTitle }}</h5>
      <div class="template-sub-title">{{ postForm.subTitle }}</div>
      <div class="template-item">
        <div class="title">{{ renderTemplateTxt.title }}：</div>
        <div class="text">{{ postForm.name }}</div>
      </div>
      <div class="template-item">
        <div class="title">备注：</div>
        <div class="text">{{ postForm.remark }}</div>
      </div>
    </div>

    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100px" class="tweets-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="推送模板" prop="templateType">
            <el-select
              v-model="postForm.templateType"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="模板副标题" prop="subTitle">
            <el-input v-model="postForm.subTitle" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="推送标题" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="推送备注" prop="remark">
            <el-input v-model="postForm.remark" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="模板消息链接" prop="newsUrl">
            <el-input v-model.trim="postForm.newsUrl" />
            <div class="form-tips text-warning">请根据推送模板填写正确的模板消息链接。</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item class="text-center">
            <el-button type="primary" @click="submitForm">下一步</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-divider v-if="isEditTask" direction="vertical" />
            <el-button
              v-if="isEditTask"
              type="warning"
              icon="el-icon-s-promotion"
              :loading="pushBtnLoading"
              :disabled="pushBtnLoading"
              @click="pushTemplateTask"
            >推送任务</el-button>
            <el-divider v-if="isEditTask" direction="vertical" />
            <el-button
              v-if="isEditTask"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="removeTweet"
            >删除任务</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getTemplatesMsgs,
  addTemplatesMsgs,
  editTemplatesMsgs,
  removeTemplatesMsgs,
  pushTemplateTask
} from '@/api/templatesMsgs'

const defaultForm = {
  id: undefined,
  templateType: '',
  name: '',
  subTitle: '',
  remark: '',
  newsUrl: ''
}

export default {
  name: 'TemplateMsgTweetsStep1',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      taskId: '',
      taskState: null,
      templateOptions: [
        {
          name: '会议上线提醒',
          id: 1
        },
        {
          name: '会议开始提醒',
          id: 2
        },
        {
          name: '会后调研推送',
          id: 3
        }
      ],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        templateType: [
          { required: true, message: '请选择推送模板', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入推送标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入推送备注', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字', trigger: 'blur' }
        ],
        newsUrl: [
          { required: true, message: '请输入模板消息链接', trigger: 'blur' }
        ]
      },
      pushBtnLoading: false
    }
  },
  computed: {
    isEditTask() {
      return this.taskState === 0 && this.isEdit
    },
    renderTemplateTxt() {
      const templateTxt = {
        templateTitle: '',
        title: ''
      }
      if (this.postForm.templateType === 1) {
        templateTxt.templateTitle = '会议提醒'
        templateTxt.title = '会议主题'
      } else if (this.postForm.templateType === 2) {
        templateTxt.templateTitle = '会议提醒'
        templateTxt.title = '会议主题'
      } else if (this.postForm.templateType === 3) {
        templateTxt.templateTitle = '问卷接收成功通知'
        templateTxt.title = '问卷主题'
      }
      return templateTxt
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.taskId = id
      this.fetchData(id)
    }
  },
  methods: {
    fetchData(id) {
      getTemplatesMsgs({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.postForm.id = data[0].id
        this.postForm.name = data[0].name
        this.postForm.subTitle = data[0].subTitle
        this.postForm.templateType = data[0].templateType
        this.postForm.remark = data[0].remark
        this.postForm.newsUrl = data[0].newsUrl
        this.taskState = data[0].state
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editTemplatesMsgs(this.postForm).then(response => {
              // console.log(response)
              this.loading = false
              this.$router.push(`/template-msgs/edit/${this.taskId}?step=2`)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addTemplatesMsgs(this.postForm).then(response => {
              // console.log(response)
              const { data } = response
              this.loading = false
              this.$router.push(`/template-msgs/edit/${data.taskId}?step=2`)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    },
    pushTemplateTask() {
      this.$confirm('确定推送此任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pushBtnLoading = true
        pushTemplateTask({
          taskId: this.taskId
        }).then(response => {
          // console.log(response)
          this.$message({
            type: 'success',
            message: '推送任务成功!',
            duration: 5000
          })
          this.pushBtnLoading = false
          this.taskState = 1
        }).catch(err => {
          console.log(err)
          this.pushBtnLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消推送'
        })
      })
    },
    removeTweet() {
      this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTemplatesMsgs({
          taskId: this.taskId
        }).then(response => {
          // console.log(response)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.$router.go(-1)
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 40px 140px;
}
.template-preview {
  width: 600px;
  line-height: initial;
  padding: 20px;
  margin: 0 auto 40px;
  border: 2px solid #efeff2;
  border-radius: 4px;
  overflow: hidden;
  .template-title {
    margin: 0;
    font-size: 16px;
  }
  .template-sub-title {
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333;
  }
  .template-item {
    display: flex;
    line-height: 2;
    font-size: 14px;
    color: #333;
    .title {
      width: 80px;
    }
    .text {
      flex: 1;
      color: #ec7644;
    }
  }
}
</style>
